package com.study.study.pool;


import cn.hutool.core.thread.NamedThreadFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zhang
 * @version 1.0
 * @date 2019/6/14 0014
 * @since jdk1.8
 */
public class Pool {

    private static final Logger LOG = LoggerFactory.getLogger(Pool.class);

    public static void main(String[] args) throws InterruptedException {
        //获取CPU核心线程数
        int coreSize = Runtime.getRuntime().availableProcessors();

        System.out.println(coreSize);

        Thread.sleep(500L);
        //创建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                coreSize,//核心线程数
                coreSize * 3,//最大线程个数，普遍设置io阻塞型 coreSize * 2,CPU型（计算型） coreSize * 1
                20L, //最大线程数存活时间
                TimeUnit.SECONDS,//最大线程数存活时间单位
                new ArrayBlockingQueue<>(10),//缓存阻塞队列
                new NamedThreadFactory("workTask", false),//线程池中线程名称 workTask-thread*
                new ThreadPoolExecutor.CallerRunsPolicy()//线程池任务拒绝策略，当前拒绝策略是当线程池满的时候，使用提交任务线程执行任务线程
        );

        for (int i = 0; i < 3000; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    LOG.info("我是你爸爸");
                }
            });
        }
        new Thread(() -> {
            for (; ; ) {
                LOG.info("当前线程池：总任务数：{},剩余任务：{},完成任务数：{},执行中的任务数：{},线程池{}",
                        pool.getTaskCount(), pool.getQueue().size(), pool.getCompletedTaskCount(), pool.getActiveCount(), pool);
                try {
                    Thread.sleep(10000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "监控").start();

        Thread.sleep(3000000L);
        for (int i = 0; i < 4000000; i++) {
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(30L);
                        LOG.info("任务线程：{}", Thread.currentThread().getName());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }

        pool.shutdown();
    }
}
